package com.allwees.bs.c.module.user.controller;

import com.allwees.bs.c.common.auth.AuthResult;
import com.allwees.bs.c.module.base.controller.BaseController;
import com.allwees.bs.c.module.base.vo.EntityFieldVo;
import com.allwees.bs.c.module.security.JwtTokenHelper;
import com.allwees.bs.c.module.user.dto.CheckResult;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.req.ChangeEmailReq;
import com.allwees.bs.c.module.user.req.ChangePasswordReq;
import com.allwees.bs.c.module.user.req.RegisterReq;
import com.allwees.bs.c.module.user.req.ResetPasswordReq;
import com.allwees.bs.c.module.user.req.SendVerifyEmailReq;
import com.allwees.bs.c.module.user.req.ThirdPartLoginReq;
import com.allwees.bs.c.module.user.req.UserProfileReq;
import com.allwees.bs.c.module.user.service.IMessageService;
import com.allwees.bs.c.module.user.service.IUserService;
import com.allwees.bs.c.module.user.service.UserCashService;
import com.allwees.bs.c.module.user.service.UserPointService;
import com.allwees.bs.core.model.user.constant.EUserSourceType;
import com.allwees.bs.core.model.user.context.CurrentUser;
import com.allwees.bs.core.modelbase.constant.ErrorMessage;
import com.allwees.bs.core.modelbase.constant.ResultEnum;
import com.allwees.bs.core.modelbase.exception.BusinessException;
import com.allwees.bs.core.modelbase.page.PageParams;
import com.allwees.bs.core.modelbase.vo.R;
import com.allwees.core.common.util.http.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;

/**
 * 和个人相关的信息
 *
 * @author jy2016
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/api/v1/user")
public class UserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IMessageService messageService;

    @Autowired
    private UserCashService userCashService;

    @Autowired
    private UserPointService userPointService;

    @Autowired
    private JwtTokenHelper jwtTokenHelper;

    /**
     * 注册
     * @param req
     * @return
     */
    @PostMapping("/register")
    public R register(@RequestBody @Validated RegisterReq req) {
        userService.register(req);
        return R.ok();
    }

    /**
     * 账户余额
     * @return
     */
    @GetMapping("/me/cash")
    public R myCash() {
        return R.ok(userCashService.getCash(getUserUuid()));
    }

    /**
     * 账户积分
     * @return
     */
    @GetMapping("/me/point")
    public R myPoint() {
        return R.ok(userPointService.getPoint(getUserUuid()));
    }

    /**
     * 第三方token登录
     *
     * @param req
     * @return
     */
    @GetMapping("/thirdPart/login")
    public R thirdPartLogin(ThirdPartLoginReq req) {
        req.setSourceType(EUserSourceType.of(RequestContext.getPlatform()));
        CheckResult checkResult = userService.checkUser(req);
        UserEntity user = checkResult.getUser();
        R r = jwtTokenHelper.genResult(user,req.getType());
        AuthResult authResult = checkResult.getAuthResult();
        r.put("type", authResult.isNewUser() ? req.getType() : null);
        r.put("isNewUser", authResult.isNewUser());
        if (authResult.getOauthUserInfo() != null) {
            r.put("oauthUserInfo", authResult.getOauthUserInfo());
        }
        return r;
    }


    /**
     * 获取自己的信息
     *
     * @return
     */
    @GetMapping("/me")
    public R me() {
        return R.ok(userService.userInfo(getUserUuid()));
    }

    /**
     * 忘记密码,发送邮件
     *
     * @param email
     * @return
     */
    @GetMapping("/forget-password")
    public R forgetPassword(@NotBlank(message = "email " + ErrorMessage.PARAM_NOT_NULL) String email) {
        userService.forgetPassword(email);
        return R.ok();
    }

    /**
     * 重置密码
     *
     *  code = 101, message = "已经被使用"
     * code = 102, message = "已过期"
     * code = 103, message = "sid 不匹配")
     * @param req
     * @return
     */
    @PutMapping("/reset-password")
    public R resetPassword(@Validated @RequestBody ResetPasswordReq req) {
        userService.resetPassword(req);
        return R.ok();
    }

    /**
     * 上传头像
     *
     * @param field
     * @return
     */
    @PutMapping("/upload/avatar")
    public R uploadAvatar(@Validated @RequestBody EntityFieldVo field) {
        userService.uploadAvatar(getUserUuid(), field.getField());
        return R.ok("client.user.upload_avatar.success");
    }


    /**
     * 更新用户信息
     * @param userProfileReq
     * @return
     */
    @PutMapping("/update/profile")
    public R updateProfile(@Validated @RequestBody UserProfileReq userProfileReq) {
        userService.updateProfile(getUserUuid(), userProfileReq);
        return R.ok("client.user.upload_user_profile.success");
    }


    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/profile")
    public R profile() {
        return R.ok(userService.findProfileByUuid(getUserUuid()));
    }

    /**
     * 获取用户消息
     *
     * @param req
     * @return
     */
    @GetMapping("/message")
    public R getMessageList(PageParams req) {
        return R.ok(messageService.getUserMessage(getUserUuid(), req));
    }

    /**
     * 标记已读
     *
     * @param messageUuid
     * @return
     */
    @PostMapping("/message/{messageUuid}/read")
    public R read(@NotBlank @PathVariable String messageUuid) {
        return R.ok(messageService.read(messageUuid));
    }

    /**
     * 修改密码
     *
     * @param req
     * @return
     */
    @PostMapping("/change-password")
    public R changePassword(@RequestBody ChangePasswordReq req) {
        userService.changePassword(CurrentUser.getUser().getUserUuid(), req);
        return R.ok("client.user.change_password.success");
    }

    /**
     * 修改 Email
     *
     * @param req
     * @return
     */
    @PostMapping("/change-email")
    public R changeEmail(@RequestBody ChangeEmailReq req) {
        userService.changeEmail(CurrentUser.getUser().getUserUuid(), req);
        return R.ok("client.user.change_email.success");
    }

    /**
     * 发送邮件验证email
     *
     * @param req
     * @return
     */
    @PostMapping("/send-verify-email")
    public R sendVerifyEmail(@RequestBody SendVerifyEmailReq req) {
        if (StringUtils.equalsIgnoreCase(CurrentUser.getUser().getUsername(),req.getEmail())){
            throw BusinessException.getInstance(ResultEnum.USERS_CHANGE_EMAIL_WITH_SAME);
        }

        if(userService.emailExists(req.getEmail())){
            throw BusinessException.getInstance(ResultEnum.USERS_CHANGE_EMAIL_WITH_EXISTS);
        }

        userService.sendVerifyEmail(CurrentUser.getUser().getUserUuid(), req);
        return R.ok("client.user.send_verify_code.success");
    }

    /**
     * 是否默认密码
     */
    @PostMapping("/is-default-password")
    public R isDefaultPwd() {
        boolean defaultPassword = userService.isDefaultPassword(CurrentUser.getUser().getUserUuid());
        return R.ok(defaultPassword);
    }

    /**
     * 注销
     * @return
     */
    @DeleteMapping("/logout")
    public R logout() {
        jwtTokenHelper.invalidateToken(CurrentUser.getUser());
        return R.ok();
    }
}
